package com.feizhoutuobang.shapeline.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.feizhoutuobang.shapeline.bo.Article;
import com.feizhoutuobang.shapeline.bo.ArticleImage;
import com.feizhoutuobang.shapeline.bo.Image;
import com.feizhoutuobang.shapeline.dao.ImageDao;
import com.feizhoutuobang.shapeline.util.Guid;

public class ImageDaoImpl extends HibernateDaoSupport implements ImageDao {

	@Override
	public Image getImageBySrc(String src) {
		String hql = "from Image where src=:src";
		Query query = getSession().createQuery(hql).setString("src", src);
		return (Image)query.uniqueResult();
	}

	@Override
	public void insertImage(Image image) {
		
		getHibernateTemplate().save("Image", image);
	}

	@Override
	public void addImageOnArticle(Article article, Image image) {
		ArticleImage ai = new ArticleImage();
		ai.setId(Guid.newId());
		ai.setArticleId(article.getId());
		ai.setImageId(image.getId());
		getHibernateTemplate().save("ArticleImage", ai);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Image> getImagesOfArticle(Article article) {
		String hql = "from Image where id in (select imageId from ArticleImage where articleId=:articleId)";
		
		Query query = getSession().createQuery(hql).setString("articleId", article.getId());
		return query.list();
	}

}
